// Redis driver for session manager
// Copyright (C) 2011-2012 Jani Kajala. Licensed under MIT-license.
// Dependencies: Node.js, redis

var redis = require( 'redis' );

//--------------------------------------------------------------------
// Redis session store
//--------------------------------------------------------------------

/** 
 * Redis session store. Default Redis key prefix is 'ses_'.
 * @param expires Expires in seconds. Default is day (86400).
 */
function SessionStoreRedis( expires, host, port, prefix ) {
	var self = this;
	this.expires = (typeof expires == 'undefined' ? 86400 : expires );
	this.prefix = (typeof prefix == 'undefined' ? 'ses.' : prefix );
	this.client = redis.createClient( port, host );
	
	// check that sid.next exists
	this.client.incr(this.prefix+"next", function(err,sid) {
		if (err) {
			self.client.set( this.prefix+"next", 1 );
			//console.log( "SessionStoreRedis: next reset. "+err );
		}
	} );
}

/** 
 * Starts new session.
 * @param ses Session doc
 * @param expires Expires in ms
 * @param next Callback next(err,sid).
 */
SessionStoreRedis.prototype.insert = function( ses, next ) {
	var self = this;
	//console.log( "SessionStoreRedis.insert: "+JSON.stringify(ses) );
	this.client.incr(this.prefix+"next", function(err,sid) {
		//console.log( "SessionStoreRedis.insert done: sid="+sid );
		ses._id = sid;
		self.client.setex(this.prefix+sid, self.expires, JSON.stringify(ses), function(err,v) {
			//console.log( "Session.Redis.insert: setex results "+err+", "+v+", sid="+sid );
			next(err,sid);
		} );
	} );
};

/** 
 * Set session data.
 * @param sid Session id 
 * @param data Session doc
 * @param next Callback next(err).
 */
SessionStoreRedis.prototype.set = function( sid, ses, next ) {
	//console.log( "SessionStoreRedis.set: sid="+sid+", ses="+JSON.stringify(ses) );
	ses._id = sid;
	this.client.setex(this.prefix+sid, this.expires, JSON.stringify(ses), next );
};

/** 
 * Get session data.
 * @param sid Session id 
 * @param next Callback next(err,ses), where data is session doc.
 */
SessionStoreRedis.prototype.get = function( sid, next ) {
	//console.log( "SessionStoreRedis.get: sid="+sid );
	this.client.get(this.prefix+sid, function(err,json) {
		//console.log( "SessionStoreRedis.prototype.get, err="+err+", json=" ); console.dir( json );
		if (err || o === null)
			return next(err,null);
		var o = JSON.parse(json);
		if (o)
			o._id=sid; 
		next(null,o);
	} );
};

/** 
 * Destroys session data.
 * @param sid Session id 
 * @param next Callback next(err)
 */
SessionStoreRedis.prototype.remove = function( sid, next ) {
	//console.log( "SessionStoreRedis.remove: sid="+sid );
	this.client.del(this.prefix+sid, next );
};

//------------------------------------------------------------------------------------------------
// module.exports
//------------------------------------------------------------------------------------------------

module.exports = SessionStoreRedis;
